#include "proto/codec.h"
#include "proto/dispatcher.h"

#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpClient.h"
#include "muduo/net/EventLoopThread.h"
#include "muduo/base/CountDownLatch.h"

#include "request/request.pb.h"
#include "response/response.pb.h"

#include <thread>

class Client
{
public:
    typedef std::shared_ptr<TranslateRequest> TranslateRequestPtr;
    typedef std::shared_ptr<CalculateRequest> CalculateRequestPtr;
    typedef std::shared_ptr<TranslateResponse> TranslateResponsePtr;
    typedef std::shared_ptr<CalculateResponse> CalculateResponsePtr;

public:
    Client(int port, const std::string& ip = "127.0.0.1") :
        _base_loop_ptr(_loop_thread.startLoop()),
        _client(_base_loop_ptr, muduo::net::InetAddress(ip, port), "client"),
        _downlatch(1),
        _dispatcher(std::bind(&Client::onUnknownMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)),
        _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        // 1. 给请求分发器注册业务处理函数
        _dispatcher.registerMessageCallback<TranslateResponse>(std::bind(&Client::onTranslateMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _dispatcher.registerMessageCallback<CalculateResponse>(std::bind(&Client::onCalculateMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        // 2. 给服务器设置连接建立和断开时的回调 & 消息回调
        _client.setConnectionCallback(std::bind(&Client::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void connect()
    {
        _client.connect();
        _downlatch.wait();
    }

    void translate(const std::string& msg)
    {
        TranslateRequestPtr req = std::make_shared<TranslateRequest>();
        req->set_content(msg);
        send(req);
    }

    void calculate(int num1, int num2, int op)
    {
        CalculateRequestPtr req = std::make_shared<CalculateRequest>();
        req->set_num1(num1);
        req->set_num2(num2);
        req->set_op('+');
        send(req);
    }

private:
    // 发送请求函数
    void send(const MessagePtr& message)
    {
        if(_conn)
            _codec.send(_conn, *message);
    }

private:
    // 当连接建立和断开时的回调
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            _conn = conn;
            _downlatch.countDown();
        }
        else
        {
            _conn.reset();
        }
    }   

    // 对于未知响应的回调函数
    void onUnknownMessage(const muduo::net::TcpConnectionPtr& conn, const MessagePtr& message, muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }

    // 当接收到翻译响应时的回调
    void onTranslateMessage(const muduo::net::TcpConnectionPtr& conn, const TranslateResponsePtr& message, muduo::Timestamp)
    {
        LOG_INFO << "TranslateResponse: " << message->content();
    }

    // 当接收到计算响应时的回调
    void onCalculateMessage(const muduo::net::TcpConnectionPtr& conn, const CalculateResponsePtr& message, muduo::Timestamp)
    {
        LOG_INFO << "CalculateResponse: " << message->result();
    }

private:
    muduo::net::EventLoopThread _loop_thread;
    muduo::net::EventLoop* _base_loop_ptr;
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _downlatch;
    
    ProtobufDispatcher _dispatcher; // 请求分发器
    ProtobufCodec _codec; // 协议处理器
};

int main()
{
    Client client(8080, "127.0.0.1");
    client.connect();
    client.translate("hello"); // 翻译业务
    client.calculate(10, 20, '-'); // 计算业务
    std::this_thread::sleep_for(std::chrono::seconds(5));
    return 0;
}